import React, { useReducer, useEffect } from 'react'
import Search from '../../components/Search/Search'
import { initState, actions, reducer, getList, getN,getId,getName,getArr } from './reducer'
import './cate.css'
import List from '../../components/List/List'
import { getCate, getGoods } from '../../request/api'

export default function Cate(props) {
    const [state, dispatch] = useReducer(reducer, initState)
    useEffect(() => {
        getCate().then(res => {
            if (res.code === 200) {
                dispatch(actions.changeList(res.list))
            }
        })

        getGoods({ fid: getId(state) }).then(res => {
            if(res.code === 200){
                dispatch(actions.changeArr(res.list))
            }
        })
    }, [getId(state)])
    let changeState = (index,name,id) => {
        dispatch(actions.changeN(index))
        dispatch(actions.changeName(name))
        dispatch(actions.changeId(id))
    }
    return (
        <div className="Cate_warp">
            <div className="cate_search">
                <Search></Search>
            </div>
            <div className="cate_con">
                <div className="cate_con_l">
                    <ul>
                        <li>本周特惠</li>
                        {
                            getList(state).map((item, index) => {
                                return <li key={item.id} onClick={() => changeState(index,item.catename,item.id)} className={getN(state) === index ? "active_left" : ''}>{item.catename}</li>
                            })
                        }
                    </ul>
                </div>
                <div className="cate_con_r">
                
                    <div className="cate_r_box">
                        <div className="cate_r_box_title">{getName(state)}</div>
                        
                        <List {...props} arr={getArr(state)}></List>
                    </div>
                </div>
            </div>
        </div>
    )
}
